#include "gatewayconfigureview.h"
#include "ui_gatewayconfigureview.h"
#include <QJsonObject>
#include <QDebug>
#include <QFile>
#include <QJsonDocument>

GatewayConfigureView::GatewayConfigureView(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::GatewayConfigureView)
{
    ui->setupUi(this);
    setWindowTitle("网关配置");
}

GatewayConfigureView::~GatewayConfigureView()
{
    delete ui;
}

void GatewayConfigureView::on_pushButton_clicked()
{
    QListWidgetItem *item = new QListWidgetItem();
    GatewayConfigurePage *gatewayConfPage = new GatewayConfigurePage;
    gatewayConfPages.append(gatewayConfPage);
    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, gatewayConfPage);
}

void GatewayConfigureView::on_pushButton_2_clicked()
{
    if (ui->listWidget->currentRow() < 0)
    {
        return;
    }
    QListWidgetItem *item = ui->listWidget->currentItem();
    ui->listWidget->removeItemWidget(item);
    delete gatewayConfPages.at(ui->listWidget->currentRow());
    gatewayConfPages.removeAt(ui->listWidget->currentRow());
    delete item;
}

void GatewayConfigureView::on_applyButton_clicked()
{
    QFile file("gatewayConf.json");
    if (!file.open(QIODevice::WriteOnly))
    {
        return;
    }
    for (int i = 0; i < ui->listWidget->count(); i++)
    {
        GatewayConfigurePage *gatewayConfPage = gatewayConfPages.at(i);
        QJsonObject jsonObj = gatewayConfPage->getConf();
        QJsonDocument jsonDoc;
        jsonDoc.setObject(jsonObj);
        QByteArray byteArray = jsonDoc.toJson(QJsonDocument::Compact);
        QString conf = QString(byteArray) + "\n";
        file.write(conf.toLatin1());
    }
    file.close();
}

void GatewayConfigureView::initView(QVector<QJsonObject> *gatewaysConf)
{
    for (int i = 0; i < gatewaysConf->length(); i++)
    {
        QJsonObject jsonObj = gatewaysConf->at(i);
        QListWidgetItem *item = new QListWidgetItem();
        GatewayConfigurePage *gatewayConfPage = new GatewayConfigurePage;
        gatewayConfPage->setConf(jsonObj);//设置网关配置页
        gatewayConfPages.append(gatewayConfPage);
        ui->listWidget->addItem(item);
        ui->listWidget->setItemWidget(item, gatewayConfPage);
    }
}
